import json  
import requests  
import os

# 定义 JSON 文件的路径  
json_file_path = 'url.json'  
  
# 打开 JSON 文件并读取内容  
try:
    with open(json_file_path, 'r', encoding='utf-8') as json_file:  
        data_dict = json.load(json_file)  
except Exception as e:
    print(f"读取 JSON 文件时出错: {e}")
    exit(1)

songs = data_dict.get('msg', {}).get('songs', [])

def download_resource(url, local_filename):
    """通用下载函数"""
    try:
        if os.path.exists(local_filename):
            print(f"文件已存在: {local_filename}")
            return
        response = requests.get(url, stream=True)
        response.raise_for_status()

        with open(local_filename, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
    except requests.exceptions.RequestException as e:
        print(f"下载文件 {local_filename} 时出错: {e}")

def download_song(song):
    id = song.get('id')
    if id is None:
        print("缺少 ID")
        return
    
    title = song.get('title', '未知标题')
    url = song.get('url')
    pic = song.get('pic')
    lrc = song.get('lrc')

    if not url or not pic or not lrc:
        print(f"歌曲 {title} 缺少下载链接")
        return

    directory_path = f'陈一发/{title}' 
    ensure_directory_exists(directory_path)
    
    local_filename = f'{directory_path}/{title}.mp3'
    local_picname = f'{directory_path}/{title}.jpg'
    local_lrcname = f'{directory_path}/{title}.lrc'
    
    download_resource(url, local_filename)
    download_resource(pic, local_picname)
    download_resource(lrc, local_lrcname)

def ensure_directory_exists(path):  
    if not os.path.exists(path):
        os.makedirs(path)
        print(f"创建了目录: {path}")
    else:
        print(f"目录已存在: {path}")

for song in songs:
    download_song(song)